package com.guaoran.source.mybatis.statement;

import com.guaoran.source.mybatis.config.Configuration;
import com.guaoran.source.mybatis.config.MapperRegistory;
import com.guaoran.source.mybatis.result.ResultSetHandler;
import lombok.Data;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/5/25 23:18
 */
@Data
public class StatementHandler {
    private Configuration configuration;
    private ResultSetHandler resultSetHandler;

    public StatementHandler(Configuration configuration) {
        this.configuration = configuration;
        this.resultSetHandler = new ResultSetHandler(configuration);
    }

    public <T> T query(MapperRegistory.MapperData mapperData, Object parameter) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(String.format(mapperData.getSql(), Long.parseLong(String.valueOf(parameter))));
        preparedStatement.execute();
        return resultSetHandler.handle(preparedStatement.getResultSet(),mapperData.getType());
    }

    public Connection getConnection() throws SQLException {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mybais_demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
